/* eslint-disable */

import React from 'react'
import uPlot from 'uplot'

import 'uplot/dist/uPlot.min.css'

import barPlugin from './uplot-bar-plugin'
import uPlotVerticalLinePlugin from './uplot-verticalline-plugin'

let statesDisplay3 = [
  {},
  {
    true: { color: '#67C23A' },
    false: { color: '#F56C6C' }
  },
  {
    true: { color: '#67C23A' },
    false: { color: '#F56C6C' }
  }
]

let frames3 = [
  [
    [0, 4.8, 9.6, 14.4, 19.2, 24],
    [true, null, false, null, true]
  ],
  [
    [0, 2.6, 7.8, 10.4, 21.2, 24],
    [false, null, true, null, false]
  ]
]

function unsetSameFutureValues(series) {
  series.forEach((values, i) => {
    if (i == 0) return

    let prevVal = values[0]

    for (let i = 1; i < values.length; i++) {
      let value = values[i]

      if (value === null) prevVal = null
      else {
        if (value === prevVal) values[i] = undefined
        else if (value != null) prevVal = value
      }
    }
  })

  return series
}

let data3 = uPlot.join(
  frames3,
  frames3.map(f => [1, 1])
)

let d = unsetSameFutureValues(data3.map(s => s.slice()))

console.log(d)

let time = 0

class SingleChart extends React.PureComponent {
  componentDidMount() {
    this.init()
  }

  init() {
    const options = {
      width: 400,
      height: 120,
      drawOrder: ['series', 'axes'],
      scales: {
        x: {
          time: false
        }
      },
      legend: {
        show: false,
      },
      axes: [{}, {}],
      series: [
        {
          label: 'Time'
        },
        {
          label: 'Device C'
        },
        {
          label: 'Device D'
        }
      ],
      plugins: [
        barPlugin({
          count: d.length - 1,
          mode: 1,
          fill: (seriesIdx, dataIdx, value) =>
            statesDisplay3[seriesIdx][value].color,
          stroke: (seriesIdx, dataIdx, value) =>
            statesDisplay3[seriesIdx][value].color
        }),
        uPlotVerticalLinePlugin(),
      ]
    }
    this.chart = new uPlot(options, d, document.getElementById('chart'))

    setInterval(() => {
      if (!this.chart) return

      time+=0.1
      
      this.chart.verticalLineNeedUpdate = true;
      this.chart.verticalLines = [time];

      this.chart.redraw()
    }, 100)
  }

  destroy() {
    if (this.chart) {
      this.chart.destroy()
    }
  }

  componentWillUnmount() {
    this.destroy()
  }

  render() {
    return pug`
      div(id="chart" style={ width: '400px', height: '300px'})
    `
  }
}

export default SingleChart
